package edu.washington.cs.workflow.analysis.guistructure.uievents;

import org.uispec4j.Panel;
import org.uispec4j.Spinner;
import org.uispec4j.UIComponent;

import edu.washington.cs.workflow.analysis.guistructure.uievents.UIEvent.UIAction;
import edu.washington.cs.workflow.analysis.guistructure.uievents.UIEvent.WINDOW;
import edu.washington.cs.workflow.util.Utils;

//XXX no setValue support
public class SpinnerEvent extends AbstractUIEvent  {

	private final Spinner spinner;
	private final UIAction action;
	
	private final String text;
	
	public SpinnerEvent(Spinner spinner, Panel panel, UIAction action, String text) {
		Utils.checkNotNull(spinner);
		Utils.checkNotNull(panel);
		Utils.checkNotNull(action);
		Utils.checkTrue(action.equals(UIAction.Nextvalue)
				|| action.equals(UIAction.Prevalue) || action.equals(UIAction.SetText)
				, "illegal action: " + action);
		if(action.equals(UIAction.SetText)) {
			Utils.checkNotNull(text);
		} else {
			Utils.checkTrue(text == null);
		}
		this.spinner = spinner;
		this.setCurrentPanel(panel);
		this.action = action;
		this.text = text;
	}
	
	@Override
	public UIComponent getUIComponent() {
		return this.spinner;
	}

	@Override
	public UIAction getAction() {
		return this.action;
	}

	public String getText() {
		return this.text;
	}
	
	@Override
	public String toString() {
		return this.action + " Spinner, text: " + this.text;
	}

	@Override
	protected WINDOW probeWindowInfoInternal() {
		return WINDOW.NONE;
	}
	
	@Override
	public boolean canFireEvent() {
		return this.spinner.isEnabled().isTrue();
	}
	
	@Override
	protected UIEventOutcome fireEventInternal() {
		
		UIEventOutcome outcome = new UIEventOutcome();
		Throwable error = null;
		try {
			if(action.equals(UIAction.Prevalue)) {
				this.spinner.clickForPreviousValue();
			} else if (action.equals(UIAction.Nextvalue)) {
				this.spinner.clickForNextValue();
			} else if (action.equals(UIAction.SetText)) {
				this.spinner.setValue(this.text);
			}
		}  catch (Throwable e) {
			error = e;
		}
		
		if(error != null) {
		    outcome.setError(error);
		}
		outcome.currentPanelClosed(super.isCurrentPanelClosed());
		return outcome;
	}

}
